package com.tuni.birthdaymoney.web.controller;

import java.security.Principal;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tuni.birthdaymoney.persistence.entity.NotificationSettings;
import com.tuni.birthdaymoney.service.SettingsService;
import com.tuni.birthdaymoney.service.UserService;
import com.tuni.birthdaymoney.web.model.MasterPage;
import com.tuni.birthdaymoney.web.model.NotificationSettingsPage;

@Controller
public class NotificationSettingsController {

    @Autowired
    private SettingsService settingsService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/settings/notification", method = RequestMethod.GET)
    public String notification_settings(Principal principal, Map<String, Object> settingsPageMap) {

        // create master page model
        MasterPage masterPageModel = new MasterPage(userService.getUserByEmail(principal.getName()), false);

        // get settings info
        NotificationSettings settings = settingsService.loadNotificationSettings();

        // create main page model
        NotificationSettingsPage notificationSettingsPageModel = new NotificationSettingsPage();
        notificationSettingsPageModel.setSettings(settings);

        // save binding
        settingsPageMap.put("masterPageModel", masterPageModel);
        settingsPageMap.put("notificationSettingsPageModel", notificationSettingsPageModel);

        return "notification_settings";
    }

    @RequestMapping(value = "/settings/notification/save", method = RequestMethod.POST)
    public String notification_settings_save(@ModelAttribute("notificationSettingsPageModel") NotificationSettingsPage settings,
            BindingResult result, Map<String, Object> settingsPageMap) {

        if (!result.hasErrors()) {
            settingsService.saveNotificationSettings(settings.getSettings());
        }

        return "redirect:/home.html";

        // settingsPageMap.put("notificationSettingsPageModel", settings);
        // return "notification_settings";
    }
}